package com.xunyin.modules.services;


import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.xunyin.api.XunyinException;
import com.xunyin.constant.ShopConstants;
import com.xunyin.constant.SystemConfigConstants;
import com.xunyin.enums.AppFromEnum;
import com.xunyin.modules.shop.domain.YxSystemAttachment;
import com.xunyin.modules.shop.service.YxSystemAttachmentService;
import com.xunyin.modules.shop.service.YxSystemConfigService;
import com.xunyin.modules.user.domain.YxUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName 二维码相关服务
 * @Author xunyinyunshang  <3594419785@qq.com>
 * @Date 2024/5/9
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CreatShareProductService {

    private final YxSystemAttachmentService systemAttachmentService;
    private final YxSystemConfigService systemConfigService;

    /**
     * 获取分销二维码url
     * @param from 来源
     * @param userInfo 用户
     * @param siteUrl h5地址
     * @param apiUrl api地址
     * @param path 本地图片路径
     * @return url
     */
    public String getSpreadUrl(String from, YxUser userInfo, String siteUrl,
                               String apiUrl, String path){

        String spreadUrl = "";
        Long uid = userInfo.getUid();
        File newFile = new File("fx.jpg");
        File newFileT = new File("simsunb.ttf");
        try {
            if(!newFile.exists()){
                InputStream stream =  getClass().getClassLoader().getResourceAsStream("fx.jpg");
                FileUtils.copyInputStreamToFile(stream, newFile);
            }
            if(!newFileT.exists()){
                InputStream streamT =  getClass().getClassLoader()
                        .getResourceAsStream("simsunb.ttf");
                FileUtils.copyInputStreamToFile(streamT, newFileT);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new XunyinException(e.getMessage());
        }

        String name = uid + "_"+from+"_user_wap.jpg";
        YxSystemAttachment attachment = systemAttachmentService.getInfo(name);
        String fileDir = path+"qrcode"+File.separator;
        String qrcodeUrl = "";
        if(ObjectUtil.isNull(attachment)){

            //生成二维码
            //判断用户是否小程序,注意小程序二维码生成路径要与H5不一样 不然会导致都跳转到小程序问题
            if(from.equals(AppFromEnum.ROUNTINE.getValue())){
                siteUrl = siteUrl+"/distribution/";
            }else if(AppFromEnum.UNIAPPH5.getValue().equals(from)){
                String uniUrl = systemConfigService.getData(SystemConfigConstants.UNI_SITE_URL);
                siteUrl =  StrUtil.isNotBlank(uniUrl) ? uniUrl :  ShopConstants.DEFAULT_UNI_H5_URL;
                siteUrl = siteUrl+"/pages/Loading/index";
            }
            //String goPath = "/pages/Loading/index";
            File file = FileUtil.mkdir(new File(fileDir));
            /*  QrCodeUtil.generate(goPath+"?spread="+uid, 180, 180,
                    FileUtil.file(fileDir+name));*/
            QrCodeUtil.generate(siteUrl+"?spread="+uid, 180, 180,
                    FileUtil.file(fileDir+name));


            systemAttachmentService.attachmentAdd(name,String.valueOf(FileUtil.size(file)),
                    fileDir+name,"qrcode/"+name);

            qrcodeUrl = fileDir+name;
        }else{
            qrcodeUrl = attachment.getAttDir();
        }

        String spreadPicName = uid + "_"+from+"_user_spread.jpg";
        String spreadPicPath = fileDir+spreadPicName;

        YxSystemAttachment attachmentT = systemAttachmentService.getInfo(spreadPicName);

        if(ObjectUtil.isNull(attachmentT)){
            try {

                Font font =  Font.createFont(Font.TRUETYPE_FONT, newFileT);
                Font f= font.deriveFont(Font.PLAIN,20);
                //font.
                ImgUtil.pressText(//
                        newFile,
                        FileUtil.file(spreadPicPath),
                        userInfo.getNickname()+"邀您加入",
                        Color.BLACK,
                        f, //字体
                        50, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                        300, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                        0.8f//透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
                );

                ImgUtil.pressImage(
                        FileUtil.file(spreadPicPath),
                        FileUtil.file(spreadPicPath),
                        ImgUtil.read(FileUtil.file(qrcodeUrl)), //水印图片
                        -150, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                        340, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                        0.8f
                );

                systemAttachmentService.attachmentAdd(spreadPicName,
                        String.valueOf(FileUtil.size(new File(spreadPicPath))),
                        spreadPicPath,"qrcode/"+spreadPicName);

                spreadUrl = apiUrl + "/api/file/qrcode/"+spreadPicName;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            spreadUrl = apiUrl + "/api/file/" + attachmentT.getSattDir();
        }

        return spreadUrl;

    }

}
